import pymysql

from config import DBiHRM


class DBUtil(object):
    conn = None

    @classmethod
    def __get_conn(cls):
        if cls.conn is None:
            cls.conn = pymysql.connect(host=DBiHRM.iHRM_host, port=DBiHRM.iHRM_port, user=DBiHRM.iHRM_user,
                                       password=DBiHRM.iHRM_password, database=DBiHRM.iHRM_database,
                                       charset=DBiHRM.iHRM_charset)
        return cls.conn

    @classmethod
    def __close_conn(cls):
        if cls.conn:
            cls.conn.close()
            cls.conn = None

    @classmethod
    def select_conn(cls, sql):
        cursor = None
        sqlsj = None

        try:
            conn = cls.__get_conn()
            cursor = conn.cursor()
            cursor.execute(sql)
            sqlsj = cursor.fetchone()

        except Exception as e:
            print(e)
            raise e

        finally:
            if cursor:
                cursor.close()
                cls.__close_conn()
            return sqlsj

    @classmethod
    def uid_conn(cls,sql):

        cursor = None
        try:
            conn = cls.__get_conn()
            cursor = conn.cursor()
            cursor.execute(sql)
            conn.commit()

        except Exception as e:
            print(e)
            if cls.conn:
                cls.conn.rollback()
            raise e

        finally:
            if cursor:
                cursor.close()
                cls.__close_conn()

if __name__ == '__main__':
    l = DBUtil()
    print(l.select_conn("select * from bs_user"))

